package com.zsyh.jiujiu.net;

import android.util.Log;

import androidx.fragment.app.FragmentActivity;

import com.android.tu.loadingdialog.LoadingDailog;
import com.blankj.utilcode.util.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

public abstract class MyFragementObserver implements Observer<ResponseBody> {

    /**
     * 加载框
     */
    private LoadingDailog dialog;
    /**
     * 上下文
     */
    private FragmentActivity mContext;
    /**
     * 是否执行加载
     */
    private boolean isLoading;

    public MyFragementObserver(FragmentActivity mContext, boolean isLoading){
        this.mContext=mContext;
        this.isLoading=isLoading;
        LoadingDailog.Builder loadBuilder = new LoadingDailog.Builder(mContext)
                .setMessage("加载中...")
                .setCancelable(false)
                .setCancelOutside(false);
        dialog = loadBuilder.create();
    }



    /**
     * 失败回调
     *
     * @param errorMsg
     */
    protected abstract void onError(String errorMsg);

    /**
     * 成功回调
     *
     * @param
     */
    protected abstract void onSuccess(String JsonStr);

    @Override
    public void onSubscribe(Disposable d) {
        if(isLoading==true){
            dialog.show();
        }

    }

    @Override
    public void onNext(ResponseBody responseBody) {
        String body= null;
        try {
            body = responseBody.string();
            Log.e("bodysucess",body+"");
            JSONObject jsonObject=new JSONObject(body);
            if(jsonObject.getString("code").equals("0")){
                onSuccess(body);
            }else{
                ToastUtils.showShort(jsonObject.getString("msg"));
                onError(body);
            }
            dialog.dismiss();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    @Override
    public void onError(Throwable e) {
        Log.e("onerror",e.getMessage());
        onError(e.getMessage());
        ToastUtils.showShort(e.getMessage());
        dialog.dismiss();
    }

    @Override
    public void onComplete() {
        dialog.dismiss();
    }
}
